package cn.edu.hit.kg;

import cn.edu.hit.core.combine.CombineAdapter;
import cn.edu.hit.core.message.MessageAdapter;
import cn.edu.hit.kg.entity.Component;
import cn.edu.hit.kg.entity.Signal;
import cn.edu.hit.core.Document;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.edu.hit.core.Adapter.VALUE;
import static cn.edu.hit.core.combine.CombineAdapter.*;
import static cn.edu.hit.core.message.MessageAdapter.*;

/**
 * Created by Wang on 2018/8/24.
 */
public class SignalUtil {
    public static Signal transferFeatureToKG(Document document) {
        Signal signal = new Signal();
        signal.setFeatureType(document.getString(FEATURE_TYPE));
        signal.setValue(document.get(VALUE));
        Map component = Component.getByName(document.getString(COMPONENT_NAME));
        signal.setComponent(component);
        signal.setSource(document);
        return signal;
    }

    public static Signal transferFeatureToKG2(Map<String, Object> document) {
        Signal signal = new Signal();
        signal.setFeatureType(document.get(FEATURE_TYPE).toString());
        signal.setValue(document.get(VALUE));
        Map component = Component.getByName(document.get(COMPONENT_NAME).toString());
        signal.setComponent(component);
        signal.setSource(document);
        return signal;
    }

    public static Signal transferSignalToKG(Map<String, Object> document) {
        Signal signal = new Signal();
        signal.setFeatureType(document.get("portName").toString());
        signal.setValue(document.get(VALUE));
        signal.setComponent(null);
        signal.setSource(document);
        return signal;
    }

    public static List<String> unzipKGToSignalId(List<Signal> signals) {
        if (signals != null) {
            return signals.stream()
                    .flatMap(signal -> {
                        if (signal.getComponent() == null) {
                            return Stream.of(((Document) signal.getSource()).getString(PORT_ID));
                        } else {
                            List<String> channels = ((List<String>) ((Document) signal.getSource()).get(COMBINE_CHANENELS));
                            if (channels == null) {
                                return Stream.empty();
                            }
                            return channels.stream();
                        }
                    }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public static List<String> unzipSignalIdFromDocument(Document document) {
        if (document == null) return Collections.emptyList();
        if (document.containsKey(CombineAdapter.FEATURE_TYPE)) {
            return ((List<String>) document.get(COMBINE_CHANENELS));
        } else {
            return Collections.singletonList(document.getString(MessageAdapter.PORT_ID));
        }
    }
}
